package com.leilei.entity;

import org.apache.ibatis.executor.resultset.ResultSetHandler;
import org.apache.ibatis.plugin.*;

import java.sql.Statement;
import java.util.List;
import java.util.Properties;

/**
 * @author: lei
 * @date: 2025-05-20 18:06
 * @desc: MyBatis 插件：在查询结果返回后对实体对象中标记字段进行 SM4 解密
 */
@Intercepts({@Signature(type = ResultSetHandler.class, method = "handleResultSets", args = Statement.class)})
public class Sm4DecryptInterceptor implements Interceptor {

    private final EncryptProcessor processor;


    public Sm4DecryptInterceptor(EncryptProcessor processor) {
        this.processor = processor;
    }

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        // 执行原始查询，获取结果（通常是 List）
        Object result = invocation.proceed();
        if (result instanceof List) {
            @SuppressWarnings("unchecked")
            List<Object> resultList = (List<Object>) result;
            for (Object element : resultList) {
                // 对每个结果实体进行解密处理
                processor.process(element, EncryptProcessor.Mode.DECRYPT);
            }
        }
        return result;
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {
    }
}
